<?php
/**
 * Created by PhpStorm.
 * User: xiaoqi
 * Date: 18-9-18
 * Time: 下午2:54
 */

namespace App\HttpController\Api;

use EasySwoole\Config;
use Particle\Validator\Validator;
use App\Model\User;

class Login extends AbstractBase
{
    /**
     * 定义验证规则，required必须验证,optional传值才验证
     */
    protected function rules($form)
    {
        $validator = new Validator();
        $validator->optional('id')->integer();
        $validator->optional('name')->lengthBetween(6, 20)->alnum();
        $validator->optional('email')->email();
        return $validator->validate($form);
    }

    /**
     * 登陆
     */
    public function index()
    {
        $server = $this->request()->getServerParams();
        if ($server['request_method'] !== 'POST') {
            return $this->error('请求方法不允许', 405);
        }

        $posts = $this->request()->getParsedBody();
        $ret = $this->rules([
            'email'     => $posts['email'],
            'password'  => $posts['password']
        ]);
        if (!$ret->isValid()) {
            $error = $this->valideErrorFirst($ret->getMessages());
            return $this->error($error);
        }
        $secret = Config::getInstance()->getConf('SECRET');
        $user = User::where([
            ['email',  $posts['email']],
            ['password', md5($posts['email'].$secret['pwd'])],
        ])->first();

        if ($user) {
            $time = time() + 7200;
            $payload = ['uid' => $user->id, 'exp' => $time];
            $token = jwt_encode($payload, $secret['jwt'], 'HS256');
            return $this->success([
                'access_token'  => $token,
                'expires_in'    => $time
            ]);
        }
        return $this->error('账号或密码错误');
    }
}